<template>
  <div class="user-view">
    <div class="chat-container">
      <div class="chat-header">
        <h2>用户聊天</h2>
        <div class="user-info" v-if="chatStore.currentUser">
          {{ chatStore.currentUser.username }}
        </div>
      </div>
      
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="!chatStore.currentContact" class="no-contact">
          请等待客服接入...
        </div>
        <template v-else>
          <div 
            v-for="(message, index) in chatStore.currentChatMessages" 
            :key="index"
            :class="['message', message.fromUserId === chatStore.currentUser?.id ? 'sent' : 'received']"
          >
            <div class="message-content">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.createdAt || message.updatedAt) }}</div>
          </div>
        </template>
      </div>
      
      <div class="chat-input">
        <input 
          v-model="messageText" 
          type="text" 
          placeholder="请输入消息..." 
          @keyup.enter="sendMessage"
          :disabled="!chatStore.currentContact"
        />
        <button @click="sendMessage" :disabled="!chatStore.currentContact">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { useWebSocket } from '../utils/websocket';
import { useChatStore } from '../store/chat';

const chatStore = useChatStore();
const { initWebSocket, sendMessage: wsSendMessage } = useWebSocket();
const messageText = ref('');
const messagesContainer = ref(null);

// 初始化
onMounted(async () => {
  // 从本地存储获取用户信息
  const userStr = localStorage.getItem('user');
  if (userStr) {
    const user = JSON.parse(userStr);
    chatStore.setCurrentUser(user);
    
    try {
      // 初始化WebSocket - 用户端不设置自动断开
      await initWebSocket(user.username, user.teamId, false);
    } catch (error) {
      console.error('初始化失败:', error);
    }
  }
});

// 监听消息变化，自动滚动到底部
watch(() => chatStore.currentChatMessages.length, () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
});

// 发送消息
const sendMessage = () => {
  if (!messageText.value.trim() || !chatStore.currentContact) return;
  
  const success = wsSendMessage(messageText.value, chatStore.currentContact.id);
  
  if (success) {
    messageText.value = '';  // 确保这行代码执行
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};
</script>

<style scoped>
.user-view {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.chat-container {
  width: 90%;
  max-width: 800px;
  height: 90vh;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.no-contact {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #888;
  font-size: 18px;
}

.message {
  margin-bottom: 15px;
  max-width: 80%; /* 增加最大宽度 */
  display: inline-block; /* 改为行内块元素 */
  width: auto; /* 自适应宽度 */
}

.message.sent {
  margin-left: auto;
  margin-right: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message.received {
  margin-right: auto;
  margin-left: 0;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  word-break: break-word;
  display: inline-block; /* 使内容区域自适应文字长度 */
  max-width: 100%; /* 确保不超过父容器 */
}

.sent .message-content {
  background-color: #1976d2;
  color: white;
  border-top-right-radius: 4px;
}

.received .message-content {
  background-color: #e0e0e0;
  color: #333;
  border-top-left-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  text-align: right;
  display: block; /* 确保时间显示 */
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  margin-right: 10px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #1565c0;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>